<template>
  <div class="login-form">
    <h2 class="login-title">欢迎登录</h2>
    <el-form :model="loginForm" ref="loginFormRef" :rules="rules">
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="code">
        <div class="captcha-container">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            prefix-icon="Key"
          />
          <img 
            :src="captchaUrl" 
            @click="refreshCaptcha" 
            alt="验证码"
            class="captcha-img"
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary" 
          class="login-button" 
          :loading="loading"
          @click="handleSubmit"
        >
          {{ loading ? '登录中...' : '登录' }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="register-section">
      <span class="register-text">还没有账号？</span>
      <el-button 
        type="text" 
        class="register-link"
        @click="handleRegister"
      >
        立即注册
      </el-button>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { setToken } from '@/utils/auth'

export default defineComponent({
  name: 'LoginModal',
  emits: ['login-success', 'switch-to-register'],
  setup(props, { emit }) {
    const loading = ref(false)
    const loginFormRef = ref(null)
    
    const loginForm = reactive({
      username: '',
      password: '',
      code: '',
      uuid: ''
    })

    const rules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    })

    const captchaUrl = ref('')

    // 获取验证码
    const getCaptcha = async () => {
      try {
        const res = await request.get('/captchaImage')
        if (res.code === 200) {
          captchaUrl.value = 'data:image/gif;base64,' + res.img
          loginForm.uuid = res.uuid
        }
      } catch (error) {
        console.error('获取验证码失败:', error)
      }
    }

    // 刷新验证码
    const refreshCaptcha = () => {
      getCaptcha()
    }

    // 提交登录
    const handleSubmit = async () => {
      if (!loginFormRef.value) return
      
      await loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const res = await request.post('/login', loginForm)
            if (res.code === 200) {
              // 直接使用 res.token，因为后端直接将 token 放在了响应对象的根级别
              setToken(res.token)
              emit('login-success')
            } else {
              ElMessage.error(res.msg || '登录失败')
              refreshCaptcha()
            }
          } catch (error) {
            console.error('登录失败:', error)
            ElMessage.error(error.message || '登录失败')
            refreshCaptcha()
          } finally {
            loading.value = false
          }
        }
      })
    }

    // 处理注册点击
    const handleRegister = () => {
      emit('switch-to-register')
    }

    // 初始化获取验证码
    onMounted(() => {
      getCaptcha()
    })

    return {
      loginForm,
      loginFormRef,
      rules,
      loading,
      captchaUrl,
      handleSubmit,
      refreshCaptcha,
      handleRegister
    }
  }
})
</script>

<style scoped>
.login-form {
  padding: 30px;
}

.login-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
}

.register-section {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.register-text {
  font-size: 14px;
  margin-right: 4px;
}

.register-link {
  font-size: 14px;
  padding: 0 4px;
}

:deep(.register-link.el-button) {
  font-weight: 600;
}
</style> 